<!--
 * @Author: Wangtao
 * @Date: 2022-05-30 22:02:02
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-06-21 11:22:10
-->
<template>
  <div class="knowledge-box">
    <div class="container" v-show="!preview.isShow">
      <div class="top">
        <el-popover
          placement="left-start"
          title="目录"
          width="240"
          popper-class="kmGlobalTree"
          trigger="hover"
        >
          <el-tree
            :highlight-current="true"
            :data="treeData"
            node-key="_id"
            :expand-on-click-node="false"
            :default-expand-all="true"
            :show-checkbox="false"
            @node-click="nodeClick"
          >
            <span
              :class="[data.disabled && 'disabled']"
              slot-scope="{ node, data }"
            >
              <span>
                {{ node.label }}
              </span>
            </span>
          </el-tree>
          <span slot="reference">
            <span class="V7_iconfont V7_iconV7tubiao_zhishiku-zhankai"></span>
          </span>
        </el-popover>
        <div class="search">
          <el-select
            size="mini"
            class="scopeSelect"
            v-model="searchForm.keywordsType"
            filterable
            :popper-append-to-body="false"
            @change="searchFun"
          >
            <el-option
              v-for="item in selectData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            size="mini"
            class="scopeIpt"
            v-model="searchForm.keywords"
            placeholder="请输入关键词模糊搜索"
            @clear="searchFun"
            :clearable="true"
            @keyup.enter.native="searchFun"
            @change="searchChange"
          >
            <i
              slot="prefix"
              class="el-input__icon el-icon-search"
              @click="searchFun"
            ></i>
          </el-input>
        </div>
      </div>
      <div class="list">
        <div class="directory" v-if="searchTitle === ''">
          <span>所属目录：{{ directory }}</span><span>共<span class="number">{{currentCount}}</span>个结果</span>
        </div>
        <div class="directory" v-else>
           <span v-html="searchTitle"></span><span>共<span class="number">{{currentCount}}</span>个结果</span>
        </div>
        <div class="content" v-if="konwledgeList.length > 0">
          <div
            class="item clearfix"
            v-for="(item, index) in konwledgeList"
            :key="index"
          >
            <span
              class="listFlag V7_iconfont fl V7_iconV7tubiao_youxiaozhishi"
            ></span>
            <div v-html="item.title" class="fl titleItem"></div>
            <div class="fr operation" v-if="!isShowWebchatBtn">
              <span
                style="margin-right: 14px"
                class="btn"
                @click="previewFun(item)"
                >预览</span
              >
              <span class="btn" @click="copyFun(item.content)">复制</span>
            </div>
            <div class="fr operation" v-else>
              <span
                style="margin-right: 14px"
                class="btn"
                @click="previewFun(item)"
                >预览</span
              >
              <span style="margin-right: 14px" class="btn" @click="kmUse(item)"
                >使用</span
              >
              <span class="btn" @click="kmSend(item)">发送</span>
            </div>
            <div v-html="item.filterContentText" class="contentItem"></div>
            <div v-if="searchTitle !== ''" class="directoryItem">
              所属目录：{{ item.catalogLabel }}
            </div>
          </div>
          <div class="more" v-if="isShowMore" @click="moreFun">加载更多</div>
        </div>
        <div v-else class="noData">暂无数据</div>
      </div>
    </div>
    <div class="preview" v-show="preview.isShow">
      <div class="previewTop">
        <span class="previewLeft">知识预览</span>
        <div class="previewRight fr">
          <span v-if="!isShowWebchatBtn">
            <span class="btn" @click="copyFun(preview.content)">复制</span>
          </span>
          <span v-else>
            <span style="margin-right: 14px" class="btn" @click="kmUse(preview)"
              >使用</span
            >
            <span class="btn" @click="kmSend(preview)">发送</span>
          </span>
          <span class="close" @click="previewClose">X</span>
        </div>
      </div>
      <div class="previewContent">
        <div v-html="preview.title" class="contentTitle"></div>
        <div v-html="preview.content"></div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import directoryTree from '@/views/km/knowledgeBase/directoryTree.vue'
import { KmModule } from '@/store/modules/km/index'
import Clipboard from 'clipboard-js'
import { knowledgeAccess } from '@/utils/kmAccess'
import { FilterXSS } from 'xss'
import { filterContent } from '@/utils/richFilter'
@Component({
  name: 'kmGlobal',
  components: { directoryTree }
})
export default class KmGlobal extends Vue {
  [x: string]: any
  private $message: any
  private $route: any
  private $bus: any
  private visible = false

  private treeData = []

  private isShowMore = false

  private directory: any = '全部' // 目录标题

  private isShowWebchatBtn: boolean = false // 是否显示在线的按钮

  private preview: any = {
    isShow: false,
    content: '',
    title: '',
    _id: ''
  }

  private searchForm: any = {
    keywordsType: 'all',
    keywords: ''
  }

  private selectData = [
    { label: '全部', value: 'all' },
    { label: '标题', value: 'title' },
    { label: '内容', value: 'content' }
  ]

  private konwledgeList: any = []

  private currentId: string = '' // 当前知识点id

  private searchTitle: string = '' // 搜索内容

  private currentCount = 0 // 当前检索数量

  private pageData: any = {
    page: 1,
    limit: 10
  }

  @Watch('$route')
  private routeChange (to: any) {
    const routeArr = to.path.split('/') // 只有在在线待处理模块下才显示发送和使用按钮
    if (routeArr[3] === 'webchat_todo' && routeArr.length > 4 && routeArr[4] !== 'empty') {
      this.isShowWebchatBtn = true
    } else {
      this.isShowWebchatBtn = false
    }
  }

  @Watch('treeData', { immediate: true })
  private setTreeData (tree) {
    this.deepSetAccess(tree || [])
  }

  private checkHasAccess (data) {
    return knowledgeAccess(data, this.$store.state.common.session)
  }

  private deepSetAccess (list) {
    const each = (arr) => {
      arr.forEach(i => {
        const { canEdit, canShow } = this.checkHasAccess(i)
        this.$set(i, 'canEdit', canEdit);
        this.$set(i, 'canShow', canShow);
        this.$set(i, 'disabled', !canShow && !canEdit);
        if (i.children?.length > 0) {
          each(i.children)
        }
      })
    }
    each(list)
  }

  private searchFun () { // 搜索知识点
    this.searchTitle =
      this.searchForm.keywords ? `<span style="color: red">“${this.searchForm.keywords}”</span>相关的搜索结果` : ''
    this.pageData.page = 1
    this.getListData()
  }

  private replaceKeyWord (html, keyWord) {
    if (keyWord) {
      const reg = new RegExp(keyWord, 'g')
      return html.replace(reg, '<strong style="color:red; cursor: pointer">' + keyWord + '</strong>')
    }
    return html
  }

  private onPopoverShow () {
    this.visible = true
    this.pageData.page = 1
    this.getListData()
    this.getTreeData()
    this.directory = '全部'
  }

  private kmUse (content: any) { // 知识库使用
    const actionData = { url: '/im-km/action/item/show', method: 'POST', data: { isHit: false, itemId: content._id, kmType: 'inner' } }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success && res.data.row) {
        const html = filterContent(content.content)
        this.$bus.$emit('kmUse', html)
      }
    })
  }

  private kmSend (content: any) { // 知识库发送
    const actionData = { url: '/im-km/action/item/show', method: 'POST', data: { isHit: false, itemId: content._id, kmType: 'inner' } }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success && res.data.row) {
        this.$bus.$emit('sendInfo', res.data.row)
      }
    })
  }

  private previewFun (item: any) { // 知识库预览
    this.preview.isShow = true
    this.preview.content = item.content
    this.preview.title = item.title
    this.preview._id = item._id
    this.preview.contentText = item.contentText
  }

  private previewClose () { // 预览关闭
    this.preview.isShow = false
    this.preview.content = ''
    this.preview.title = ''
    this.preview._id = ''
    this.preview.contentText = ''
  }

  private nodeClick (data: any, node: any) { // 切换目录
    if (data.disabled) {
      return
    }
    this.directory = ''
    this.searchForm.keywords = '' // 切换目录清空当前搜索项
    this.searchTitle = ''
    this.getAllTitle(node)
    this.directory = this.directory.substr(0, this.directory.length - 1)
    this.pageData.page = 1
    this.currentId = data._id
    this.getListData({ currentId: data._id })
  }

  private getAllTitle (data: any) { // 处理目录
    if (data.level === 1) {
      this.directory = data.label + '/' + this.directory
      return this.directory
    }
    this.directory = data.label + '/' + this.directory
    if (data.parent) {
      this.getAllTitle(data.parent)
    }
  }

  private getListData (obj?: any) { // 获取知识库列表
    const actionData = {
      url: '/im-km/action/item/list',
      method: 'POST',
      data: {
        catalogId: obj && obj.currentId ? obj.currentId : 'all', // 有当前知识点id取当前id列表否则取全部
        kmType: 'inner',
        page: this.pageData.page,
        limit: this.pageData.limit,
        type: 'global',
        ...this.searchForm
      }
    }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        const list = res.data.list || []
        const validArr: any = []
        this.currentCount = res.data.count || 0
        list.forEach((item: any) => {
          const returnItem = item
          returnItem.filterContentText = this.replaceKeyWord(returnItem.filterContent, this.searchForm.keywords)
          if (item.status === 'valid') {
            validArr.push(returnItem);
          }
        })
        if (obj && obj.more) {
          this.konwledgeList = [...this.konwledgeList, ...validArr]
        } else {
          this.konwledgeList = validArr
        }
        if (list.length < this.pageData.limit) {
          this.isShowMore = false
        } else {
          this.isShowMore = true
        }
      }
    })
  }

  private copyFun (content: string) { // 复制事件
    if (content) {
      const copyCon = filterContent(content);
      Clipboard.copy(copyCon).then(() => {
        this.$message.success('复制成功')
      }).catch(() => {
        this.$message.error('复制失败')
      })
    }
  }

  private moreFun () { // 点击加载更多
    this.pageData.page++
    this.getListData({ currentId: this.currentId, more: true })
  }

  private getTreeData () { // 获取知识库目录列表
    const actionData = { url: '/im-km/action/catalog/list', method: 'POST', data: { kmType: 'inner' } }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.treeData = res.data.tree || []
      }
    })
  }

  private searchChange (value) {
    this.$emit('searchChange', { value, type: 'intelligentAnswer' })
  }

  public setQuestion (value) {
    this.searchForm.keywords = value
  }

  private mounted () {
    const routeArr = this.$route.path.split('/')
    if (routeArr[1] === 'im_workBench' && routeArr.length > 4 && routeArr[4] !== 'empty') {
      this.isShowWebchatBtn = true
    } else {
      this.isShowWebchatBtn = false
    }
    this.onPopoverShow();
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/common/style/common.styl'
.disabled
  cursor not-allowed
  width 100%
  display inline-block
.knowledge-box
  height 500px
.V7_iconV7tubiao_zhishiku
  font-size 18px
  cursor pointer
  color #3d4e66
.kmGlobalPoper
  .btn
    color #008BEE
    cursor pointer
  .preview
    height 500px
    .previewTop
      height 48px
      line-height 48px
      border-bottom 1px solid $border-main
      padding 0px 16px
      .previewLeft
        font-weight 600px
      .close
        color #A6A6AE
        margin-left 10px
        cursor pointer
    .previewContent
      height 440px
      overflow auto
      padding 0px 16px
      .contentTitle
        margin 16px 0px 14px 0px
        font-weight 600
        font-size 14px
        color #303753
  .container
    height 100%
    .top
      border-bottom 1px solid #ECF0F3
      padding 10px
      .V7_iconV7tubiao_zhishiku-zhankai
        color #008BEE
        cursor pointer
      .search
        display inline-block
        margin-left 10px
        width calc(100% - 27px)
        .scopeSelect
          width 80px
          >>>.el-input__inner
            border-right none
            border-radius 4px 0px 0px 4px
        .scopeIpt
          width calc(100% - 80px)
          >>>.el-input__inner
            order-left none
            border-radius 0 4px 4px 0
    .list
      height calc(100% - 70px)
      padding 10px 0px
      .directory
        padding-left 16px
        padding-right 16px
        box-sizing: border-box
        color #B3B9C7
        display: flex
        justify-content: space-between
        .number
          color: #008BEE
      .noData
        height 350px
        line-height 350px
        text-align center
        font-size 14px
      .content
        overflow auto
        height 100%
        .item
          padding 16px
          width 100%
          cursor pointer
          border-bottom 1px solid $border-main
          .listFlag
            font-size 14px
            color #008BEE
            margin-right 5px
          .titleItem
            color #303753
            font-weight 600
            margin-bottom 5px
            width calc(100% - 120px)
            overflow hidden
            text-overflow ellipsis
            white-space nowrap
          .contentItem
            padding-right 10px
            color #71798C
            width 100%
            word-wrap break-word
            display -webkit-box
            -webkit-box-orient vertical
            -webkit-line-clamp 2
            overflow hidden
          .directoryItem
            margin-top 5px
            color #71798c
            width 100%
            overflow hidden
            text-overflow ellipsis
            white-space nowrap
          .operation
            display none
        .item:hover
          background #F3F6F9
        .item:hover .operation
          display block
        .more
          text-align center
          color #008BEE
          margin-top 10px
          cursor pointer
</style>
<style lang="stylus">
.kmGlobalTree
  max-height 400px
  .el-tree
    max-height 352px
    overflow-y auto
  .el-tree-node__label
    font-size 14px
    max-width 90px
    display inline-block
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .el-tree-node__content
    margin 5px 0px
  .el-tree__empty-block
    min-height 360px
.kmGlobalPoper
  padding 0px !important
  font-size 12px !important
</style>
